package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.temporal.ChronoUnit;
import java.util.*;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.GardenUserInfo;
import com.ruoyi.system.mapper.GardenUserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.GardenFlowerMapper;
import com.ruoyi.system.domain.GardenFlower;
import com.ruoyi.system.service.IGardenFlowerService;

/**
 * 花朵信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-02
 */
@Service
public class GardenFlowerServiceImpl implements IGardenFlowerService 
{
    @Autowired
    private GardenFlowerMapper gardenFlowerMapper;
    @Autowired
    private GardenUserInfoMapper gardenUserInfoMapper;

    /**
     * 初始化或更新用户花园
     */
    public Map<String, Object> initOrUpdateUserGarden(Long wxUserId) {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> newFlowers = new ArrayList<>();
        int totalNewFlowers = 0;

        // 1. 获取用户信息
        GardenUserInfo userInfo = gardenUserInfoMapper.selectGardenUserInfoByWxId(wxUserId);
        LocalDate now = LocalDate.now();

        if (userInfo == null) {
            // 新用户，创建用户信息
            userInfo = new GardenUserInfo();
            userInfo.setWxuserId(wxUserId);
            userInfo.setStartMonth(now.getMonthValue());
            userInfo.setCreateTime(new Date());
            gardenUserInfoMapper.insertGardenUserInfo(userInfo);

            // 补充从1月到当前月的所有花朵
            for (int month = 1; month <= now.getMonthValue(); month++) {
                int daysInMonth;
                if (month == now.getMonthValue()) {
                    daysInMonth = now.getDayOfMonth();
                } else {
                    daysInMonth = YearMonth.of(now.getYear(), month).lengthOfMonth();
                }

                Map<String, Object> monthFlowers = new HashMap<>();
                monthFlowers.put("month", month);
                monthFlowers.put("count", daysInMonth);
                newFlowers.add(monthFlowers);
                totalNewFlowers += daysInMonth;

                addFlowersForMonth(wxUserId, month, 1, daysInMonth);
            }
        } else {
            // 老用户，检查是否需要添加新花
            LocalDateTime lastCheckTime = LocalDateTime.parse(userInfo.getReserve1());
            if (lastCheckTime != null) {
                LocalDate lastCheck = lastCheckTime.toLocalDate();
                long daysBetween = ChronoUnit.DAYS.between(lastCheck, now);

                if (daysBetween >= 1) {
                    if (lastCheck.getMonthValue() == now.getMonthValue()) {
                        // 同一个月
                        int newCount = now.getDayOfMonth() - lastCheck.getDayOfMonth();
                        if (newCount > 0) {
                            Map<String, Object> monthFlowers = new HashMap<>();
                            monthFlowers.put("month", now.getMonthValue());
                            monthFlowers.put("count", newCount);
                            newFlowers.add(monthFlowers);
                            totalNewFlowers += newCount;

                            addFlowersForMonth(wxUserId, now.getMonthValue(),
                                    lastCheck.getDayOfMonth() + 1, now.getDayOfMonth());
                        }
                    } else {
                        // 跨月处理
                        // 1. 上月剩余天数
                        int lastMonthDays = YearMonth.of(lastCheck.getYear(),
                                lastCheck.getMonthValue()).lengthOfMonth();
                        int lastMonthNewDays = lastMonthDays - lastCheck.getDayOfMonth();
                        if (lastMonthNewDays > 0) {
                            Map<String, Object> lastMonthFlowers = new HashMap<>();
                            lastMonthFlowers.put("month", lastCheck.getMonthValue());
                            lastMonthFlowers.put("count", lastMonthNewDays);
                            newFlowers.add(lastMonthFlowers);
                            totalNewFlowers += lastMonthNewDays;

                            addFlowersForMonth(wxUserId, lastCheck.getMonthValue(),
                                    lastCheck.getDayOfMonth() + 1, lastMonthDays);
                        }

                        // 2. 中间月份
                        for (int month = lastCheck.getMonthValue() + 1;
                             month < now.getMonthValue(); month++) {
                            int daysInMonth = YearMonth.of(now.getYear(), month).lengthOfMonth();
                            Map<String, Object> monthFlowers = new HashMap<>();
                            monthFlowers.put("month", month);
                            monthFlowers.put("count", daysInMonth);
                            newFlowers.add(monthFlowers);
                            totalNewFlowers += daysInMonth;

                            addFlowersForMonth(wxUserId, month, 1, daysInMonth);
                        }

                        // 3. 当前月
                        if (now.getDayOfMonth() > 0) {
                            Map<String, Object> currentMonthFlowers = new HashMap<>();
                            currentMonthFlowers.put("month", now.getMonthValue());
                            currentMonthFlowers.put("count", now.getDayOfMonth());
                            newFlowers.add(currentMonthFlowers);
                            totalNewFlowers += now.getDayOfMonth();

                            addFlowersForMonth(wxUserId, now.getMonthValue(), 1, now.getDayOfMonth());
                        }
                    }
                }
            }
        }

        // 更新最后检查时间
        userInfo.setReserve1(String.valueOf(LocalDateTime.now()));
        gardenUserInfoMapper.updateGardenUserInfo(userInfo);

        // 返回结果
        result.put("totalNewFlowers", totalNewFlowers);
        result.put("newFlowersByMonth", newFlowers);
        return result;
    }
//    public void initOrUpdateUserGarden(Long wxUserId) {
//        // 1. 获取用户信息
//        GardenUserInfo userInfo = gardenUserInfoMapper.selectGardenUserInfoByWxId(wxUserId);
//        LocalDate now = LocalDate.now();
//
//        if (userInfo == null) {
//            // 新用户，创建用户信息
//            userInfo = new GardenUserInfo();
//            userInfo.setWxuserId(wxUserId);
//            userInfo.setStartMonth(now.getMonthValue());
//            userInfo.setCreateTime(new Date());
//            gardenUserInfoMapper.insertGardenUserInfo(userInfo);
//
//            // 补充从1月到当前月的所有花朵
//            for (int month = 1; month <= now.getMonthValue(); month++) {
//                int daysInMonth;
//                if (month == now.getMonthValue()) {
//                    // 当前月只添加到今天
//                    daysInMonth = now.getDayOfMonth();
//                } else {
//                    // 其他月份添加整月
//                    daysInMonth = YearMonth.of(now.getYear(), month).lengthOfMonth();
//                }
//
//                addFlowersForMonth(wxUserId, month, 1, daysInMonth);
//            }
//        } else {
//            // 老用户，检查是否需要添加新花
//            LocalDateTime lastCheckTime = LocalDateTime.parse(userInfo.getReserve1());
//            if (lastCheckTime != null) {
//                LocalDate lastCheck = lastCheckTime.toLocalDate();
//                long daysBetween = ChronoUnit.DAYS.between(lastCheck, now);
//
//                if (daysBetween >= 1) {
//                    // 需要补充花朵
//                    if (lastCheck.getMonthValue() == now.getMonthValue()) {
//                        // 同一个月
//                        addFlowersForMonth(wxUserId, now.getMonthValue(),
//                                lastCheck.getDayOfMonth() + 1, now.getDayOfMonth());
//                    } else {
//                        // 跨月
//                        // 补充上个月剩余的天数
//                        int lastMonthDays = YearMonth.of(lastCheck.getYear(),
//                                lastCheck.getMonthValue()).lengthOfMonth();
//                        addFlowersForMonth(wxUserId, lastCheck.getMonthValue(),
//                                lastCheck.getDayOfMonth() + 1, lastMonthDays);
//
//                        // 补充中间的整月
//                        for (int month = lastCheck.getMonthValue() + 1;
//                             month < now.getMonthValue(); month++) {
//                            int daysInMonth = YearMonth.of(now.getYear(), month).lengthOfMonth();
//                            addFlowersForMonth(wxUserId, month, 1, daysInMonth);
//                        }
//
//                        // 补充当前月到今天
//                        addFlowersForMonth(wxUserId, now.getMonthValue(), 1, now.getDayOfMonth());
//                    }
//                }
//            }
//        }
//
//        // 更新最后检查时间
//        userInfo.setReserve1(String.valueOf(LocalDateTime.now()));
//        gardenUserInfoMapper.updateGardenUserInfo(userInfo);
//    }

    /**
     * 为指定月份添加花朵
     */
    private void addFlowersForMonth(Long wxUserId, int month, int startDay, int endDay) {
        for (int day = startDay; day <= endDay; day++) {
            GardenFlower flower = new GardenFlower();
            flower.setWxuserId(wxUserId);
            flower.setMonth(month);
            flower.setDay(day);
            // 随机位置 (20-80范围内)
            flower.setxPosition(BigDecimal.valueOf(20 + Math.random() * 60));
            flower.setyPosition(BigDecimal.valueOf(20 + Math.random() * 60));
            flower.setCreateTime(new Date());
            gardenFlowerMapper.insertGardenFlower(flower);
        }
    }

    /**
     * 更新花朵位置
     */
    public void updateFlowerPosition(Long flowerId, BigDecimal x, BigDecimal y) {
        GardenFlower flower = gardenFlowerMapper.selectGardenFlowerById(flowerId);
        if (flower == null) {
            throw new ServiceException("花朵不存在");
        }

        // 检查24小时限制
        if (flower.getLastMoveTime() != null) {
            long hours = ChronoUnit.HOURS.between(
                    flower.getLastMoveTime().toInstant(),
                    Instant.now()
            );
            if (hours > 24) {
                throw new ServiceException("该花朵已超过24小时移动限制");
            }
        }

        flower.setxPosition(x);
        flower.setyPosition(y);
        flower.setLastMoveTime(new Date());
        gardenFlowerMapper.updateGardenFlower(flower);
    }
    /**
     * 查询花朵信息
     * 
     * @param id 花朵信息主键
     * @return 花朵信息
     */
    @Override
    public GardenFlower selectGardenFlowerById(Long id)
    {
        return gardenFlowerMapper.selectGardenFlowerById(id);
    }

    /**
     * 查询花朵信息列表
     * 
     * @param gardenFlower 花朵信息
     * @return 花朵信息
     */
    @Override
    public List<GardenFlower> selectGardenFlowerList(GardenFlower gardenFlower)
    {
        return gardenFlowerMapper.selectGardenFlowerList(gardenFlower);
    }

    /**
     * 新增花朵信息
     * 
     * @param gardenFlower 花朵信息
     * @return 结果
     */
    @Override
    public int insertGardenFlower(GardenFlower gardenFlower)
    {
        gardenFlower.setCreateTime(DateUtils.getNowDate());
        return gardenFlowerMapper.insertGardenFlower(gardenFlower);
    }

    /**
     * 修改花朵信息
     * 
     * @param gardenFlower 花朵信息
     * @return 结果
     */
    @Override
    public int updateGardenFlower(GardenFlower gardenFlower)
    {
        gardenFlower.setUpdateTime(DateUtils.getNowDate());
        return gardenFlowerMapper.updateGardenFlower(gardenFlower);
    }

    /**
     * 批量删除花朵信息
     * 
     * @param ids 需要删除的花朵信息主键
     * @return 结果
     */
    @Override
    public int deleteGardenFlowerByIds(Long[] ids)
    {
        return gardenFlowerMapper.deleteGardenFlowerByIds(ids);
    }

    /**
     * 删除花朵信息信息
     * 
     * @param id 花朵信息主键
     * @return 结果
     */
    @Override
    public int deleteGardenFlowerById(Long id)
    {
        return gardenFlowerMapper.deleteGardenFlowerById(id);
    }
}
